{{define "namespaces"}}
{{template "header" .}}

<div class="container">
  <h2>Namespace</h2>
  <form>
    <fieldset>
      <legend>New Namespace</legend>
      <label>Name</label>
      <input type="text" class="input-xlarge" id="new-ns-name" placeholder="dot-separated path"></input>
      <div>
        <button type="submit" class="btn" onclick="newNamespace(); return false;">Create</button>
      </div>
    </fieldset>
  </form>

  <h3>List</h3>
  <table id="namespace-table" class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th>Namespace</th>
        <!--th>First datapoint</th>
        <th>Last</th-->
        <th>Secret</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="namespace-tbody"></tbody>
  </table>

  <div id="command"></div>
</div>

<script src="/static/api.js"></script>
<script>
function newNamespace() {
  var ns = document.getElementById('new-ns-name').value;
  console.log(ns);

  $.ajax({
    url: "/api/namespace/new",
    data: {'ns': ns},
  	dataType: 'json',
  	success: function(d) {
      setTimeout(refreshNamespaceTable, 100);
    },
    error: function(d) {
      console.log(d);
      alert(d.responseText);
    }
  });
}

function refreshNamespaceTable() {
  listNamespaces(
  	function(d) {
      console.log(d);
      var tb = document.createElement('tbody');
      tb.id='namespace-tbody';
      for (var i = 0; i < d.Namespaces.length; ++i) {
        var ns = d.Namespaces[i];
        var tr = document.createElement('tr');

        var td = document.createElement('td');
        td.textContent = ns.Name
        tr.appendChild(td);

        /*
        var td = document.createElement('td');
        td.textContent = ns.First
        tr.appendChild(td);

        var td = document.createElement('td');
        td.textContent = ns.Last
        tr.appendChild(td);
        */

        var td = document.createElement('td');
        var secret = document.createElement('a');
        secret.onclick = (function(td, ns) {
            return function() {
              td.textContent = ns.Secret;
              //alert("Use this secret to send metrics to this " +
              //  "namespace: " + ns.Secret);
              return false;
            };
        })(td, ns);
        secret.href="";
        secret.textContent = 'Reveal';
        td.appendChild(secret);
        tr.appendChild(td);

        var td = document.createElement('td');
        td.textContent = 'Delete';
        tr.appendChild(td);

        tb.appendChild(tr);
      }
      var table = document.getElementById('namespace-table');
      table.replaceChild(
        tb,
        document.getElementById('namespace-tbody'));
    },
    function(d) {
      console.log(d);
      alert(d.responseText);
    }
  );
}

refreshNamespaceTable();
</script>

{{template "footer"}}
{{end}}
